package id.ac.amikom.hticket;

import id.ac.amikom.lib.CustomAdapter;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.IntentAction;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity{
	
	JSONArray rs;
	ListAdapter adapter;
	static ArrayList<HashMap<String, Object>> list;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		
		final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(R.string.app_name);

		actionBar.setHomeAction(new IntentAction(this, MainActivity
				.createIntent(this), R.drawable.logo_hospital));
		
		String json = "[{\"rs_name\":\"RS. JIH (Jogja International Hospital)\",\"ruang\":\"Ruang 31 - Update 18m\",\"dist\":\"0.4 Km\"},{\"rs_name\":\"RSUP. Sardjito\",\"ruang\":\"Ruang 73 - Update 1d2h\",\"dist\":\"4.8 Km\"},{\"rs_name\":\"RS. Bethesda\",\"ruang\":\"Ruang 46 - Update 7h28m\",\"dist\":\"3.6 Km\"}]";
				
		try {
			int in = 1;
			list = new ArrayList<HashMap<String, Object>>();
			rs = new JSONArray(json);
			for (int i = 0; i < rs.length(); i++) {				
				JSONObject obj = rs.getJSONObject(i);
				HashMap<String,Object> map = new HashMap<String, Object>();
				
				map.put("rs", obj.getString("rs_name"));
				map.put("ruang", obj.getString("ruang"));
				map.put("dist", obj.getString("dist"));
				if(in==1) map.put("logo", R.drawable.id1);
				if(in==2) map.put("logo", R.drawable.id2);
				if(in==3) map.put("logo", R.drawable.id3);
				list.add(map);
				
				listData();
				in++;
			}	
		} catch (JSONException e) {
			e.printStackTrace();
		}				
		
		
	}
	
	public void listData() {
		adapter = new CustomAdapter(this, list, R.layout.list_layout,
				new String[] { "rs", "ruang", "dist", "logo" }, new int[] {
						R.id.name, R.id.room, R.id.dist, R.id.logo });

		setListAdapter(adapter);
		registerForContextMenu(getListView());
	}
	
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);		

		Intent in = new Intent(MainActivity.this, DetailActivity.class);		
		startActivity(in);

	}
	
	public static Intent createIntent(Context context) {
		Intent i = new Intent(context, MainActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		return i;
	}
	
}
